import { ref, onMounted, computed, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { getPublicArticles, getArticleCategories } from '/@/api/blog/articles';
import { message } from 'ant-design-vue';
import { useGlobalLoading } from '/@/hooks/blog/useGlobalLoading';

export function useBlogArticles() {
  const router = useRouter();
  const pageRef = ref<HTMLElement>();
  const showEasterEgg = ref(false);
  const searchQuery = ref('');
  const activeCategory = ref('1'); // 默认选中数据库中的"全部"分类
  const currentPage = ref(1);
  const pageSize = ref(6);
  
  // 使用全局加载状态
  const { withLoading } = useGlobalLoading();

  // 分类数据
  const categories = ref<Array<{ id: string; name: string; count: number }>>([]);

  // 文章数据
  const articles = ref([]);
  const totalArticles = ref(0);

  // 获取分类数据
  const fetchCategories = async () => {
    try {
      const res = await getArticleCategories();
      console.log('🔍 获取分类数据:', res);
      if (res && res.length > 0) {
        const categoryList = res || [];
        console.log('📊 所有分类:', categoryList);
        
        // 直接使用后端返回的分类数据，过滤掉计数为0的分类
        const validCategories = categoryList.filter((cat: any) => (cat.articleCount || cat.article_count || 0) > 0);
        categories.value = validCategories.map((cat: any) => ({
          id: cat.id.toString(),
          name: cat.name,
          count: cat.articleCount || cat.article_count || 0,
        }));
        console.log('🎯 最终分类列表:', categories.value);
      }
    } catch (error) {
      console.error('获取分类失败:', error);
    }
  };

  // 获取文章数据
  const fetchArticles = async () => {
    return withLoading(async () => {
      const params: any = {
        pageNo: currentPage.value,
        pageSize: pageSize.value,
        status: 1, // 只获取已发布的文章
      };

      // 如果有搜索关键词
      if (searchQuery.value.trim()) {
        params.title = searchQuery.value.trim();
      }

      // 如果有分类筛选
      if (activeCategory.value !== '1') {
        params.categoryId = activeCategory.value;
        console.log('🎯 分类筛选参数:', params.categoryId);
      }

      console.log('📤 请求参数:', params);
      const res = await getPublicArticles(params);
      console.log('🔍 获取文章数据:', res);

      if (res) {
        articles.value = (res.records || []).map((item) => ({
          ...item,
          tags: typeof item.tags === 'string' ? JSON.parse(item.tags) : item.tags || [],
        }));
        totalArticles.value = res.total || 0;

        // 更新分类计数
        if (activeCategory.value === '1') {
          // 找到"全部"分类并更新计数
          const allCategory = categories.value.find((cat) => cat.id === '1');
          if (allCategory) {
            allCategory.count = totalArticles.value;
          }
        }
      }
    });
  };

  // 计算属性
  const paginatedArticles = computed(() => {
    return articles.value;
  });

  // 方法
  const handleKeydown = (event: KeyboardEvent) => {
    console.log('🔤 键盘事件触发:', event.key, event.target);

    if (event.key === 'ArrowLeft') {
      console.log('⬅️ 检测到左箭头键，准备返回');
      event.preventDefault(); // 阻止默认行为
      event.stopPropagation(); // 阻止事件冒泡
      goBack();
    }
  };

  const goBack = () => {
    console.log('🔄 执行返回操作');
    try {
      // 检查历史记录长度
      console.log('📚 历史记录长度:', window.history.length);

      if (window.history.length > 1) {
        router.go(-1);
      } else {
        // 如果没有历史记录，跳转到首页
        console.log('🏠 没有历史记录，跳转到首页');
        router.push('/');
      }
    } catch (error) {
      console.error('❌ 返回失败:', error);
      // 如果router.go失败，尝试使用router.back()
      try {
        router.back();
      } catch (backError) {
        console.error('❌ router.back()也失败:', backError);
        // 最后尝试直接跳转到首页
        router.push('/');
      }
    }
  };

  const setActiveCategory = (categoryId: string) => {
    console.log('🔄 切换分类:', categoryId, '当前分类:', activeCategory.value);
    activeCategory.value = categoryId;
    currentPage.value = 1; // 重置到第一页
    console.log('📄 重置页码到第1页');
    fetchArticles();
  };

  const handleSearch = () => {
    currentPage.value = 1; // 重置到第一页
    fetchArticles();
  };

  const viewArticle = (article: any) => {
    // 跳转到文章详情页
    console.log('查看文章:', article.title);
    router.push(`/blog/articles/${article.id}`);
  };

  const handlePageChange = (page: number) => {
    currentPage.value = page;
    fetchArticles();
    // 滚动到页面顶部
    if (pageRef.value) {
      pageRef.value.scrollIntoView({ behavior: 'smooth' });
    }
  };

  const getCategoryColor = (category: string) => {
    const colorMap: Record<string, string> = {
      java: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
      spring: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      microservice: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
      database: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    };
    return colorMap[category] || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
  };

  // 初始化
  onMounted(async () => {
    await fetchCategories();
    await fetchArticles();

    // 设置页面焦点，确保键盘事件能够正确触发
    nextTick(() => {
      if (pageRef.value) {
        pageRef.value.focus();
        console.log('🎯 页面焦点已设置');
      }
    });
  });

  return {
    pageRef,
    showEasterEgg,
    searchQuery,
    activeCategory,
    currentPage,
    pageSize,
    categories,
    paginatedArticles,
    totalArticles,
    handleKeydown,
    goBack,
    setActiveCategory,
    handleSearch,
    viewArticle,
    handlePageChange,
    getCategoryColor,
  };
}
